package comgame.scenes;

import com.almasb.fxgl.app.scene.FXGLScene;
import com.almasb.fxgl.audio.AudioPlayer;
import com.almasb.fxgl.audio.Sound;
import com.almasb.fxgl.dsl.FXGL;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;

import java.net.URL;
import java.util.Objects;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.control.Label;
import javafx.scene.text.Font;
import javafx.animation.TranslateTransition;
import javafx.animation.ScaleTransition;
import javafx.animation.ParallelTransition;
import javafx.util.Duration;


public class AltarScene extends FXGLScene {
    private StackPane sceneRoot;
    public static Object[][] crops = {
        {"胡萝卜", "/assets/textures/Fruit_Carrot.png", "胡萝卜", 20, 1},
        {"土豆", "/assets/textures/Fruit_Potato.png", "土豆", 20, 1},
        {"西红柿", "/assets/textures/Fruit_Tomato.png", "番茄", 20, 1},
        {"小麦", "/assets/textures/Fruit_Wheat.png", "小麦", 20, 1},
        {"星果", "/assets/textures/Fruit_Starfruit.png", "星果", 8, 2},
        {"南瓜", "/assets/textures/Fruit_Pumpkin.png", "南瓜", 8, 2},
        {"霜瓜", "/assets/textures/Fruit_Powdermelon.png", "霜瓜", 8, 2},
        {"幽灵辣椒", "/assets/textures/Fruit_GhostPaper.png", "幽灵辣椒", 8, 2},
        {"水龙果", "/assets/textures/Fruit_WaterDragon.png", "水龙果", 8, 2},
        {"齐瓜", "/assets/textures/Fruit_Qi_Fruit.png", "齐瓜", 8, 2},
        {"洞穴鲨鱼", "/assets/textures/fish_Caveshark.png", "洞穴鲨鱼", 1, 3},
        {"世纪之花", "/assets/textures/Fruit_Plantera.png", "世纪之花", 1, 3}
    };
    public static boolean[] cropSacrificed;
    public static boolean[] cropClicked;
    public static int totalSacrificedCount = 0;
    public static int cropClickedCount = 0;
    public static int currentRound = 1;
    public static boolean newBossDefeated = false;
    public static boolean newBossUnlocked = false;
    static {
        cropSacrificed = new boolean[crops.length];
        cropClicked = new boolean[crops.length];
    }
    public AltarScene() {
        // 在构造函数中立即隐藏player实体，避免时序问题
        if (comgame.scenes.GameScene.playerEntity != null) {
            comgame.scenes.GameScene.playerEntity.getViewComponent().setVisible(false);
        }
        sceneRoot = new StackPane();
        sceneRoot.setPrefSize(800, 600);
        sceneRoot.setStyle("-fx-background-color: transparent;");
        // 加载背景图片
        Image backgroundImg;
        try {
            backgroundImg = new Image(Objects.requireNonNull(
                getClass().getResourceAsStream("/assets/textures/AltarScene.png")));
        } catch (Exception e) {
            System.err.println("背景图片加载异常: " + e.getMessage());
            backgroundImg = null;
        }
        if (backgroundImg != null) {
            ImageView background = new ImageView(backgroundImg);
            background.setFitWidth(1000);
            background.setFitHeight(750);
            sceneRoot.getChildren().add(background);
        }
        // 添加作物展示区
        addCropShowcase();
        // 添加返回按钮
        addBackButton();
        // 添加Dasima按钮
        addDasimaButton();
    }
    public void addBackButton() {
        AudioPlayer audioPlayer = FXGL.getAudioPlayer();
        Sound clickSound = FXGL.getAssetLoader().loadSound("drop.wav");
        Button backBtn = createSingleImageButton(
                "/assets/textures/backbutton.png",
                "返回",
                0.1
        );
        StackPane.setAlignment(backBtn, Pos.TOP_LEFT);
        StackPane.setMargin(backBtn, new Insets(20, 0, 0, 20));
        backBtn.setOnMouseClicked(e -> {
            audioPlayer.playSound(clickSound);
            FXGL.getGameScene().clearUINodes();
            MapScene mapScene = new MapScene();
            FXGL.getGameScene().addUINode(mapScene.getSceneRoot());
            // 确保player实体可见
            if (comgame.scenes.GameScene.playerEntity != null) {
                comgame.scenes.GameScene.playerEntity.getViewComponent().setVisible(true);
            }
        });
        sceneRoot.getChildren().add(backBtn);
    }

    // 添加Dasima按钮的方法
    public void addDasimaButton() {
        // 加载按钮音效
        AudioPlayer audioPlayer = FXGL.getAudioPlayer();
        Sound clickSound = FXGL.getAssetLoader().loadSound("pop.wav");

        // 创建Dasima按钮
        Button dasimaBtn = createSingleImageButton(
                "/assets/textures/DaSiMa.png",
                "Dasima",
                15 // 缩放比例，可根据图片大小调整
        );

        // 设置按钮位置（左下角）
        StackPane.setAlignment(dasimaBtn, Pos.BOTTOM_LEFT);
        StackPane.setMargin(dasimaBtn, new Insets(0,0, 50, 20));  // 左下角边距，往上移动50像素

        // 绑定点击事件
        dasimaBtn.setOnMouseClicked(e -> {
            audioPlayer.playSound(clickSound);  // 播放点击音效
            System.out.println("Dasima按钮被点击！");

            // 显示个性化消息
            showDasimaDialog();
        });

        // 将按钮添加到场景
        sceneRoot.getChildren().add(dasimaBtn);
    }

    // 显示Dasima个性化对话框
    public void showDasimaDialog() {
        // 创建遮罩层
        StackPane overlay = new StackPane();
        overlay.setStyle("-fx-background-color: rgba(0,0,0,0.7);");
        overlay.setPrefSize(sceneRoot.getWidth(), sceneRoot.getHeight());

        // 弹窗主体
        StackPane dialog = new StackPane();
        dialog.setStyle("-fx-background-color: linear-gradient(to bottom right, #FFE4C4, #FFD700); -fx-background-radius: 20; -fx-border-radius: 20; -fx-border-color: #DAA520; -fx-border-width: 3;");
        dialog.setPadding(new Insets(40));
        dialog.setMaxWidth(400);
        dialog.setMaxHeight(450);  // 增加高度以容纳更多文字

        // Dasima图片
        Image dasimaImg = new Image(Objects.requireNonNull(getClass().getResourceAsStream("/assets/textures/DaSiMa.png")));
        ImageView dasimaView = new ImageView(dasimaImg);
        dasimaView.setFitWidth(80);
        dasimaView.setFitHeight(80);

        // 个性化消息
        Label messageLabel = new Label("欢迎来到祭坛！\n我是大祭司，\n这里可以进行作物献祭，\n献祭分为三轮\n完成献祭可以突破传送门，\n点击作物进行献祭");
        messageLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold; -fx-text-fill: #8B4513; -fx-text-alignment: center;");
        messageLabel.setWrapText(true);
        messageLabel.setMaxWidth(400);  // 设置最大宽度确保文字能够正确换行

        // 关闭按钮
        Button closeBtn = new Button("开始献祭！");
        closeBtn.setStyle("-fx-background-color: #DAA520; -fx-text-fill: white; -fx-font-weight: bold; -fx-font-size: 16px; -fx-background-radius: 10; -fx-border-radius:10; -fx-padding:10;");
        closeBtn.setOnAction(e -> sceneRoot.getChildren().remove(overlay));

        // 按钮布局
        HBox buttonBox = new HBox(15, closeBtn);
        buttonBox.setAlignment(Pos.CENTER);

        // 布局
        VBox dialogContent = new VBox(20, dasimaView, messageLabel, buttonBox);
        dialogContent.setAlignment(Pos.CENTER);
        dialog.getChildren().add(dialogContent);
        overlay.getChildren().add(dialog);
        StackPane.setAlignment(dialog, Pos.CENTER);

        // 添加到场景
        sceneRoot.getChildren().add(overlay);
    }
    public void addCropShowcase() {
        // 只在二阶段全部献祭完且Boss未击败时显示传送门
        if (currentRound == 2 && !newBossDefeated && isSecondRoundAllSacrificed()) {
            showPortalAndWaitForClick();
            return;
        }
        // 如果Boss已击败且当前是第二轮，自动进入第三轮
        if (currentRound == 2 && newBossDefeated && isSecondRoundAllSacrificed()) {
            currentRound = 3;
        }
        HBox row1 = new HBox(30);
        row1.setAlignment(Pos.CENTER);
        HBox row2 = new HBox(30);
        row2.setAlignment(Pos.CENTER);
        int displayedCount = 0;
        for (int i = 0; i < crops.length; i++) {
            final int idx = i;
            int requiredAmount = (Integer)crops[i][3];
            int round = (Integer)crops[i][4];
            // 只显示当前轮次的作物
            if (round != currentRound) continue;
            VBox cropBox = new VBox(8);
            cropBox.setAlignment(Pos.CENTER);
            // 洞穴鲨鱼图片放大
            int imgSize = ("洞穴鲨鱼".equals(crops[i][0])) ? 120 : 60;
            ImageView img = new ImageView(new Image(Objects.requireNonNull(getClass().getResourceAsStream((String)crops[i][1])),imgSize,imgSize,false,true));
            // 特殊处理洞穴鲨鱼，它不在ItemManager中，而是在FishpoolScene中
            int count;
            if ("洞穴鲨鱼".equals(crops[i][2])) {
                count = comgame.scenes.FishpoolScene.caveSharkCount;
            } else {
                count = comgame.scenes.ItemManager.getInstance().getItemCount((String)crops[i][2]);
            }
            Label countLabel = new Label(count + "/" + requiredAmount);
            countLabel.setFont(Font.font("Arial", 18));
            countLabel.setStyle("-fx-text-fill: #fff; -fx-font-weight: bold; -fx-effect: dropshadow(one-pass-box, #000, 2, 0, 1, 1);");
            cropBox.getChildren().addAll(img, countLabel);
            // 高亮与点击动画
            if (count >= requiredAmount && !cropSacrificed[idx]) {
                img.setStyle("-fx-effect: dropshadow(gaussian, yellow, 18, 0.7, 0, 0);");
                img.setCursor(javafx.scene.Cursor.HAND);
                img.setOnMouseClicked(e -> {
                    if (cropClicked[idx]) return;
                    cropClicked[idx] = true;
                    cropSacrificed[idx] = true;
                    totalSacrificedCount++;
                    // 数量-requiredAmount，隐藏文字
                    if ("洞穴鲨鱼".equals(crops[idx][2])) {
                        // 洞穴鲨鱼从FishpoolScene中移除
                        comgame.scenes.FishpoolScene.caveSharkCount -= requiredAmount;
                    } else {
                        comgame.scenes.ItemManager.getInstance().removeItem((String)crops[idx][2], requiredAmount);
                    }
                    countLabel.setVisible(false);
                    // 动画：移动到背景中央再向上
                    double centerX = sceneRoot.getWidth() / 2;
                    double centerY = sceneRoot.getHeight() / 2 - 60;
                    double imgSceneX = img.localToScene(img.getBoundsInLocal()).getMinX() + img.getFitWidth()/2;
                    double imgSceneY = img.localToScene(img.getBoundsInLocal()).getMinY() + img.getFitHeight()/2;
                    double dx = centerX - imgSceneX;
                    double dy = centerY - imgSceneY;
                    TranslateTransition move = new TranslateTransition(Duration.seconds(0.7), img);
                    move.setByX(dx);
                    move.setByY(dy);
                    ScaleTransition scale = new ScaleTransition(Duration.seconds(0.7), img);
                    scale.setToX(2.0);
                    scale.setToY(2.0);
                    ParallelTransition pt = new ParallelTransition(move, scale);
                    pt.setOnFinished(ev -> {
                        img.setVisible(false);
                        cropClickedCount++;
                        // 检查当前轮次是否完成
                        int currentRoundCount = 0;
                        for (int j = 0; j < crops.length; j++) {
                            if ((Integer)crops[j][4] == currentRound && cropSacrificed[j]) {
                                currentRoundCount++;
                            }
                        }
                        int currentRoundTotal = 0;
                        for (int j = 0; j < crops.length; j++) {
                            if ((Integer)crops[j][4] == currentRound) {
                                currentRoundTotal++;
                            }
                        }
                        if (currentRoundCount == currentRoundTotal) {
                            // 当前轮次完成，进入下一轮或出现传送门
                            if (currentRound == 2 && !newBossDefeated) {
                                // 第二阶段完成，出现传送门
                                showPortalAndWaitForClick();
                            } else if (currentRound < 3) {
                                currentRound++;
                                cropClickedCount = 0;
                                // 重新加载场景
                                FXGL.getGameScene().clearUINodes();
                                AltarScene altarScene = new AltarScene();
                                FXGL.getGameScene().addUINode(altarScene.getSceneRoot());
                            } else {
                                // 三轮全部完成，跳转到END界面
                                FXGL.getGameScene().clearUINodes();
                                EndScene endScene = new EndScene();
                                FXGL.getGameScene().addUINode(endScene.getSceneRoot());
                            }
                        }
                    });
                    pt.play();
                });
            } else if (cropSacrificed[idx]) {
                // 已献祭的作物显示为灰色
                img.setOpacity(0.3);
                countLabel.setVisible(false);
            }
            if (displayedCount < 6) {
                row1.getChildren().add(cropBox);
            } else {
                row2.getChildren().add(cropBox);
            }
            displayedCount++;
        }
        // 补空位
        while (row1.getChildren().size() < 6) {
            row1.getChildren().add(new VBox());
        }
        while (row2.getChildren().size() < 6) {
            row2.getChildren().add(new VBox());
        }
        VBox cropsArea = new VBox(18, row1, row2);
        cropsArea.setAlignment(Pos.TOP_CENTER);
        cropsArea.setPadding(new Insets(35, 0, 0, 0));
        sceneRoot.getChildren().add(cropsArea);
    }

    // 修改：传送门点击直接进入Boss战
    public void showPortalAndWaitForClick() {
        // 添加前先移除已有传送门
        sceneRoot.getChildren().removeIf(node -> node instanceof ImageView && "portal".equals(node.getId()));
        Image portalImg = new Image(Objects.requireNonNull(getClass().getResourceAsStream("/assets/textures/BossTeleport.png")));
        ImageView portalView = new ImageView(portalImg);
        portalView.setFitWidth(220);
        portalView.setFitHeight(220);
        portalView.setStyle("-fx-cursor: hand;");
        portalView.setId("portal"); // 设置唯一ID，便于查找和移除
        StackPane.setAlignment(portalView, Pos.CENTER);
        sceneRoot.getChildren().add(portalView); // 默认在最顶层
        portalView.setOnMouseClicked(e -> {
            sceneRoot.getChildren().remove(portalView);
            FXGL.getGameScene().clearUINodes();
            // 弹出Boss关卡详情UI
            LevelData.LevelInfo bossInfo = LevelData.getInstance().getLevelInfo(8);
            LevelDetailUI bossDetail = new LevelDetailUI(
                bossInfo,
                () -> {
                    FXGL.getGameScene().clearUINodes();
                    new CombatScene(8, () -> {
                        FXGL.getGameScene().clearUINodes();
                        MapScene mapScene = new MapScene();
                        FXGL.getGameScene().addUINode(mapScene.getSceneRoot());
                    });
                },
                () -> {
                    FXGL.getGameScene().clearUINodes();
                    MapScene mapScene = new MapScene();
                    FXGL.getGameScene().addUINode(mapScene.getSceneRoot());
                }
            );
            FXGL.getGameScene().addUINode(bossDetail);
        });
    }
    private Button createSingleImageButton(String imagePath, String text, double scale) {
        // 修正路径：确保以斜杠开头
        if (!imagePath.startsWith("/")) {
            imagePath = "/" + imagePath;
        }

        // 通过URL加载（可抛出详细异常）
        URL imageUrl = getClass().getResource(imagePath);
        if (imageUrl == null) {
            throw new RuntimeException("资源未找到: " + imagePath);
        }

        // 计算目标尺寸
        Image rawImage = new Image(imageUrl.toExternalForm());
        double targetWidth = rawImage.getWidth() * scale;
        double targetHeight = rawImage.getHeight() * scale;

        // ✅ 高质量预缩放
        Image buttonImage = new Image(
                imageUrl.toExternalForm(),
                targetWidth, targetHeight, true, true, true
        );

        ImageView imageView = new ImageView(buttonImage);
        Button button = new Button();
        button.setGraphic(imageView);
        button.setPrefSize(imageView.getFitWidth(), imageView.getFitHeight());
        button.setStyle("-fx-background-color: transparent; -fx-border-color: transparent;");
        DropShadow shadow = new DropShadow();
        shadow.setColor(Color.WHITE);
        shadow.setRadius(10);
        button.setOnMouseEntered(e -> {
            button.setEffect(shadow);
            button.setOpacity(0.9);
        });
        button.setOnMouseExited(e -> {
            button.setEffect(null);
            button.setOpacity(1.0);
        });
        button.setOnMousePressed(e -> {
            button.setOpacity(0.8);
            button.setScaleX(0.98);
            button.setScaleY(0.98);
        });
        button.setOnMouseReleased(e -> {
            button.setOpacity(0.9);
            button.setScaleX(1.0);
            button.setScaleY(1.0);
        });
        return button;
    }
    public StackPane getSceneRoot() {
        return sceneRoot;
    }
    public static int getCropRound(int idx) {
        return (Integer)crops[idx][4];
    }

    public static boolean isSecondRoundAllSacrificed() {
        for (int i = 0; i < crops.length; i++) {
            if (getCropRound(i) == 2 && !cropSacrificed[i]) {
                return false;
            }
        }
        return true;
    }
    public static void resetAltarProgress() {
        cropSacrificed = new boolean[crops.length];
        cropClicked = new boolean[crops.length];
        totalSacrificedCount = 0;
        cropClickedCount = 0;
        currentRound = 1;
        newBossDefeated = false;
        newBossUnlocked = false;
    }
}
